﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Threading;
using ArgusLib.Xml;

namespace Fraktalysator
{
	static class UpdateChecker
	{
#if DEBUG
		const string UpdateInfoUrl = "https://dl.dropboxusercontent.com/u/104710622/Fraktalysator/UpdateInfosDebug.xml";
#else
		const string UpdateInfoUrl = "https://dl.dropboxusercontent.com/u/104710622/Fraktalysator/UpdateInfos.xml";
#endif

		public static void GetUpdates(Action<UpdateInfo[]> callback)
		{
			//UpdateInfo[] infos2 = new UpdateInfo[] { new UpdateInfo() };
			//using (FileStream file = new FileStream("UpdateInfos.xml", FileMode.Create))
			//{
			//	using (Serializer ser = Serializer.FromStream(file, "Fraktalysator"))
			//	{
			//		ser.Serialize("UpdateInfos", infos2);
			//	}
			//}
			//return;
			ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
				{
					UpdateInfo[] infos = UpdateChecker.DownloadUpdateInfos();
					infos = UpdateChecker.GetUpdates(infos);
					callback(infos);
				}));
		}

		private static UpdateInfo[] DownloadUpdateInfos()
		{
			try
			{
				WebRequest request = WebRequest.Create(UpdateChecker.UpdateInfoUrl);
				WebResponse response = request.GetResponse();
				using (Stream stream = response.GetResponseStream())
				{
					using (Deserializer des = Deserializer.FromStream(stream))
					{
						string name;
						object updateInfos = des.Deserialize(out name);
						if (name != "UpdateInfos")
							return null;
						else
							return (UpdateInfo[])updateInfos;
					}
				}
			}
			catch (WebException)
			{
				return null;
			}
		}

		private static UpdateInfo[] GetUpdates(IEnumerable<UpdateInfo> updateInfos)
		{
			if (updateInfos == null)
				return null;
			Version currentVersion = ArgusLib.Environment.GetAssemblyVersion();
			List<UpdateInfo> RetVal = new List<UpdateInfo>();
			foreach (UpdateInfo info in updateInfos)
			{
				if (currentVersion < info.Build)
					RetVal.Add(info);
			}
			return RetVal.ToArray();
		}
	}
}
